package com.tancire.framework.aspectj;

import com.tancire.common.annotation.Client;
import com.tancire.common.constant.Constants;
import com.tancire.common.enums.UserSource;
import com.tancire.common.exception.ServiceException;
import com.tancire.common.utils.ServletUtils;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

/**
 * @author chenchao
 * @version 1.0
 * @since 2024/7/30 23:37
 */
@Aspect
@Component
public class ClientAspect {

    /**
     * 进入前校验
     *
     * @param client
     */
    @Before("@annotation(client)")
    public void doBefore(Client client) {
        UserSource value = client.value();
        int currentUserSource = getCurrentUserSource();
        if (value.getCode() != currentUserSource) {
            throw new ServiceException("非法请求");
        }
    }

    /**
     * 获取当前请求头数据
     *
     * @return
     */
    private int getCurrentUserSource() {
        try {
            String us = ServletUtils.getRequest().getHeader(Constants.TANCIRE_SOURCE_KEY);
            return Integer.parseInt(us);
        } catch (Exception e) {
            throw new ServiceException("非法请求");
        }
    }
}
